package com.library.service;

import com.library.bean.ReaderCard;
import com.library.constant.CommonConstant;
import com.library.controller.RCException;
import com.library.entity.*;
import com.library.mapper.OaApproveMapper;
import com.library.mapper.OaAttendanceRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ido
 * @since 2024-12-14
 */

@Service
public class OaAttendanceRecordServiceImpl {
    private final static Logger log = LoggerFactory.getLogger(LoginService.class);

    @Autowired
    private OaAttendanceRecordMapper oaAttendanceRecordMapper;
    @Autowired
    private OaApproveMapper oaApproveMapper;

    // 查看自己的打卡记录
    public List<OaAttendanceRecordExt> list(OaAttendanceRecordExt oaDepartmentUserLink) {
        long readerId = CommonUtils.getLoginReaderCard().getReaderId();
        OaAttendanceRecordExt query = new OaAttendanceRecordExt();
        query.setUserInfoId(readerId);
        List<OaAttendanceRecordExt> oaAttendanceRecordExts = this.oaAttendanceRecordMapper.listByQuery(query);
        for (OaAttendanceRecordExt oaAttendanceRecordExt : oaAttendanceRecordExts) {
            if (CommonConstant.recordStatus_qingjia.equals(oaAttendanceRecordExt.getStatus())) {
                //请假
            } else {
                Date startTime = oaAttendanceRecordExt.getStartTime();
                Date endTime = oaAttendanceRecordExt.getEndTime();
                oaAttendanceRecordExt.setLate(isTimeAfterNineAM(startTime));
                if (startTime != null && endTime != null) {
                    long time = endTime.getTime();
                    long time1 = startTime.getTime();
                    long differenceInMillis = time - time1;
                    long differenceInSeconds = Math.abs(differenceInMillis / 1000);
                    oaAttendanceRecordExt.setEarly(differenceInSeconds > 8*60*60);
                }
            }
        }
        return oaAttendanceRecordExts;
    }


    public static boolean isTimeAfterNineAM(Date startTime) {
        // 获取当前日期的Calendar实例
        Calendar nowCalendar = Calendar.getInstance();
        nowCalendar.setTime(startTime);

        // 获取startTime的Calendar实例
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(startTime);

        // 重置nowCalendar的时间部分为当天的9点
        nowCalendar.set(Calendar.HOUR_OF_DAY, 9);
        nowCalendar.set(Calendar.MINUTE, 0);
        nowCalendar.set(Calendar.SECOND, 0);
        nowCalendar.set(Calendar.MILLISECOND, 0);

        // 比较startTime是否晚于当天的9点
        return startCalendar.after(nowCalendar);
    }

    public void add(OaAttendanceRecordReq oaDepartmentUserLink) {
        Date recordDate = oaDepartmentUserLink.getRecordDate();
        Integer status = oaDepartmentUserLink.getStatus();
        Calendar calendar = CommonUtils.getCalendarYYYYMMDD(recordDate);
        // 获取修改后的时间
        Date yyyymmdd = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置为GMT+8时区
        Date now = new Date();
        log.info("Current time in GMT+8: 当前时间" + sdf.format(now));
        log.info("Current time in GMT+8:  打卡时间 " + sdf.format(recordDate));
        log.info("Current time in GMT+8:  打卡日期 " + sdf.format(yyyymmdd));

        ReaderCard loginReaderCard = CommonUtils.getLoginReaderCard();
        if (loginReaderCard == null) {
            throw new RCException("你还没有登录 请先登录");
        }
        OaAttendanceRecordExt query = new OaAttendanceRecordExt();
        long readerId = loginReaderCard.getReaderId();
        query.setUserInfoId(readerId);
        query.setRecordDate(yyyymmdd);
        List<OaAttendanceRecordExt> oaAttendanceRecordExts = this.oaAttendanceRecordMapper.listByQuery(query);
        OaApproveExt oaApproveExt = new OaApproveExt();
        oaApproveExt.setUserInfoId(readerId);
        oaApproveExt.setRecordDate(yyyymmdd);
        oaApproveExt.setStatus(CommonConstant.approve_don);
        List<OaApproveExt> oaApproveExts = this.oaApproveMapper.exists(oaApproveExt);
        if (CommonConstant.clockInButton.equals(oaDepartmentUserLink.getStatus())) {
            in(oaAttendanceRecordExts, recordDate, yyyymmdd, oaApproveExts, loginReaderCard);
        } else if (CommonConstant.clockOutButton.equals(oaDepartmentUserLink.getStatus())) {
            out(oaAttendanceRecordExts, recordDate, yyyymmdd, oaApproveExts, loginReaderCard);
        }
    }


    public void in(List<OaAttendanceRecordExt> oaAttendanceRecordExts,
                   Date recordDate,
                   Date yyyymmdd,
                   List<OaApproveExt> oaApproveExts,
                   ReaderCard loginReaderCard
    ) {
        Boolean qingjia = false;
        if (!oaApproveExts.isEmpty()) {
            qingjia = true;
        }

        //上班
        if (oaAttendanceRecordExts.isEmpty()) {
            OaAttendanceRecord record = new OaAttendanceRecord();
            record.setRecordDate(yyyymmdd);
            record.setStartTime(recordDate);
            record.setEndTime(null);
            record.setUserInfoId(loginReaderCard.getReaderId());
            record.setStatus(qingjia ? CommonConstant.recordStatus_qingjia : CommonConstant.recordStatus_normal);
            int insert = this.oaAttendanceRecordMapper.insertSelective(record);
        } else {
            OaAttendanceRecordExt oaAttendanceRecordExt = oaAttendanceRecordExts.get(0);
            //上班
            if (oaAttendanceRecordExt.getEndTime() == null) {
                OaAttendanceRecord record = new OaAttendanceRecord();
                record.setId(oaAttendanceRecordExt.getId());
                record.setStartTime(recordDate);
                int i = this.oaAttendanceRecordMapper.updateByPrimaryKeySelective(record);
            } else {
                throw new RCException("已经打了下班卡（已经下班了）");
            }

        }
    }

    public void out(List<OaAttendanceRecordExt> oaAttendanceRecordExts,
                    Date recordDate,
                    Date yyyymmdd,
                    List<OaApproveExt> oaApproveExts,
                    ReaderCard loginReaderCard
    ) {
//        下班
        if (oaAttendanceRecordExts.isEmpty()) {
            //下班
            throw new RCException("上班卡 还没打,请先打上班卡");
        } else {
            OaAttendanceRecordExt oaAttendanceRecordExt = oaAttendanceRecordExts.get(0);
//
            //下班
            if (oaAttendanceRecordExt.getStartTime() != null) {
                OaAttendanceRecord record = new OaAttendanceRecord();
                record.setId(oaAttendanceRecordExt.getId());
                record.setEndTime(recordDate);
                long differenceInMillis = recordDate.getTime() - oaAttendanceRecordExt.getStartTime().getTime();
                long differenceInSeconds = Math.abs(differenceInMillis / 1000);
                if(differenceInSeconds > 8*60*60){
                    differenceInSeconds = 8*60*60 - differenceInSeconds;
                }else{
                    differenceInSeconds = 0l;
                }
                record.setTotalTime(differenceInSeconds);
                int i = this.oaAttendanceRecordMapper.updateByPrimaryKeySelective(record);
            } else {
                throw new RCException("上班卡 还没打,请先打上班卡");
            }
        }
    }

    public void update(OaAttendanceRecord oaDepartmentUserLink) {
        int i = this.oaAttendanceRecordMapper.updateByPrimaryKeySelective(oaDepartmentUserLink);
    }

    public OaAttendanceRecord detail(OaAttendanceRecord oaAttendanceRecord) {
        return this.oaAttendanceRecordMapper.selectByPrimaryKey(oaAttendanceRecord.getId());
    }


    public OaAttendanceRecordExt detailByLast(OaAttendanceRecord oaDepartmentUserLink) {
        ReaderCard loginReaderCard = CommonUtils.getLoginReaderCard();
        if (loginReaderCard == null) {
            throw new RCException("你还没有登录 请先登录");
        }
        OaAttendanceRecordExt query = new OaAttendanceRecordExt();
        query.setRecordDate(new Date());
        query.setUserInfoId(loginReaderCard.getReaderId());
        List<OaAttendanceRecordExt> oaAttendanceRecordExts = this.oaAttendanceRecordMapper.listByQuery(query);
        if (oaAttendanceRecordExts.isEmpty())
            return null;
        else {
            return oaAttendanceRecordExts.get(0);
        }
    }

    public List<OaAttendanceRecordStaticVo> statics(OaAttendanceRecordExt oaDepartmentUserLink) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        Date month = null;
        try {
            month = simpleDateFormat.parse(oaDepartmentUserLink.getMonth());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (month == null) {
            month = new Date();
        }
        int attendanceDaysInMonth = getAttendanceDaysInMonth(month);
        /*
            -- 当月出勤天数 = 当月除请假以外的打卡记录
            -- 当月请假天数 = 查当月审批
            -- 当月缺勤天数 = 当月应出勤 - 当月出勤天数
         */
        ReaderCard loginReaderCard = CommonUtils.getLoginReaderCard();
        if (loginReaderCard == null) {
            return new ArrayList<>();
        }
        String role = loginReaderCard.getRole();
        long readerId = loginReaderCard.getReaderId();

        String monthStr = simpleDateFormat.format(month);

        List<OaAttendanceRecordStaticVo> oaAttendanceRecordStaticVos = this.oaAttendanceRecordMapper.listStatics(monthStr, role, readerId);
        // 查询请假
        List<OaAttendanceRecordStaticVo> oaAttendanceRecordStaticVos1 = this.oaApproveMapper.listStatics(monthStr, role, readerId);
        for (OaAttendanceRecordStaticVo oaAttendanceRecordStaticVo : oaAttendanceRecordStaticVos) {
            // 缺勤天数
            oaAttendanceRecordStaticVo.setQueqingcount(attendanceDaysInMonth - oaAttendanceRecordStaticVo.getChuqincount());
            for (OaAttendanceRecordStaticVo attendanceRecordStaticVo : oaAttendanceRecordStaticVos1) {
                if (oaAttendanceRecordStaticVo.getUserInfoId().equals(attendanceRecordStaticVo.getUserInfoId())) {
                    oaAttendanceRecordStaticVo.setQingjiacount(attendanceRecordStaticVo.getQingjiacount());
                    continue;
                }
            }
        }
        return oaAttendanceRecordStaticVos;
    }

    /**
     * 计算当前月份的工作日天数（不包括周末）。
     *
     * @param date 当前日期
     * @return 当前月份的工作日天数
     */
    public static int getAttendanceDaysInMonth(Date date) {
        Calendar calendar = Calendar.getInstance(); // 获取当前日历实例
        calendar.setTime(date); // 设置给定的日期

        int year = calendar.get(Calendar.YEAR); // 年份
        int month = calendar.get(Calendar.MONTH); // 月份，从0开始计数

        // 如果给定日期在当前月，计算到当前日期为止的应出勤天数
        boolean isCurrentMonth = (year == Calendar.getInstance().get(Calendar.YEAR)) &&
                (month == Calendar.getInstance().get(Calendar.MONTH));
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 该月的总天数
        int attendanceDays = 0;

        for (int day = 1; day <= (isCurrentMonth ? Calendar.getInstance().get(Calendar.DAY_OF_MONTH) : daysInMonth); day++) {
            Calendar index = Calendar.getInstance();
            index.set(year, month, day);
            if (index.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY &&
                    index.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
                attendanceDays++;
            }
        }
        return attendanceDays;
    }

    public static void main(String[] args) {
        // 测试函数，使用当前日期
        Date currentDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            currentDate = simpleDateFormat.parse("2024-12-20");
            int workDays = getAttendanceDaysInMonth(currentDate);
            System.out.println("当前月份的工作日天数: " + workDays);

            currentDate = simpleDateFormat.parse("2024-10-20");
            int workDays1 = getAttendanceDaysInMonth(currentDate);
            System.out.println("当前月份的工作日天数: " + workDays1);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }


}
